package com.shxy.rlzy.security;

import com.shxy.rlzy.entity.User;
import com.shxy.rlzy.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @program: rlzy
 * @description: 用户查询实现类
 * @author: tanhao
 * @create: 2021-08-19 15:52
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.getByUsername(username);
        if(user == null) {
            throw new UsernameNotFoundException("用户名或密码有误");
        }

        return new AccountUser(user.getId(), user.getUsername(), user.getPassword(), getUserAuthorities(user.getId()));
    }

    /**
     * 获取用户权限（角色和菜单）
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthorities(Long userId) {
        // 角色(ROLE_admin)、菜单操作权限(sys:user:list)
        String authorities = userService.getUserAuthorities(userId); // 角色权限列表，用逗号隔开
        // 使用工具封装成权限对象列表
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authorities);
    }
}
